import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-15-0:02
 */
public class 关于CompletableFutureのsupplyAsync {
  public static ExecutorService executor = Executors.newFixedThreadPool(10);

  /**
   * 如果发起一个【supplyAsync】异步任务后
   * 后面还要发起其它的异步任务
   * 只要不在这个【supplyAsync】任务发起之后 马上future.get
   * 那么是不会阻塞当前线程的, 后面的异步任务也会马上发起
   *
   * 但一旦调用 future.get, 当前线程后面的代码就不会执行了, 直到拿到结果
   * */

  public static void main(String[] args) throws ExecutionException, InterruptedException {
    /*System.out.println("main...start...");
    CompletableFuture<Integer> future01 = CompletableFuture
      .supplyAsync(() -> {
        System.out.println("任务1线程开始");
        int i = 10 / 2;
        //int i = 10 / 0;
        System.out.println("运行结果: " + i);
        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println("任务1线程结束");
        return i;
      }, executor);
    System.out.println("main中future1之后的代码");
    Integer integer = future01.get();
    System.out.println("future01.get(): " + integer);


    CompletableFuture<String> future02 = CompletableFuture
      .supplyAsync(() -> {
        System.out.println("任务2线程开始");
        System.out.println("任务2线程结束");
        return "Hello";
      }, executor);
    System.out.println("main中future2之后的代码");
    String s = future02.get();
    System.out.println("future02.get(): "+s);
    System.out.println("main...end...");*/
/*
main...start...
main中future1之后的代码
任务1线程开始
运行结果: 5
任务1线程结束
future01.get(): 5
main中future2之后的代码
任务2线程开始
任务2线程结束
future02.get(): Hello
main...end...
* */


    /** 不立马future01.get()*/
    System.out.println("main...start...");
    CompletableFuture<Integer> future01 = CompletableFuture
      .supplyAsync(() -> {
        System.out.println("任务1线程开始");
        int i = 10 / 2;
        //int i = 10 / 0;
        System.out.println("运行结果: " + i);
        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println("任务1线程结束");
        return i;
      }, executor);



    System.out.println("main中future1之后的代码");



    CompletableFuture<String> future02 = CompletableFuture
      .supplyAsync(() -> {
        System.out.println("任务2线程开始");
        System.out.println("任务2线程结束");
        return "Hello";
      }, executor);


    System.out.println("main中future2之后的代码");


    Integer integer = future01.get();
    System.out.println("future01.get(): " + integer);
    String s = future02.get();
    System.out.println("future02.get(): "+s);
    System.out.println("main...end...");
/*
main...start...
main中future1之后的代码
任务1线程开始
运行结果: 5
main中future2之后的代码
任务2线程开始
任务2线程结束
任务1线程结束
future01.get(): 5
future02.get(): Hello
main...end...
* */
  }
}
